package cn.szzsi._webpc;

import cn.szzsi._Config;
import cn.szzsi._web.BaseWebController;
import cn.szzsi._web.QRCodeUtil;
import cn.szzsi.common.bean.CartItemCookie;
import cn.szzsi.common.bean.SystemConfig.PointType;
import cn.szzsi.common.bean.SystemConfig.StoreFreezeTime;
import cn.szzsi.common.bean.WeixinConfig;
import cn.szzsi.common.bean.dto.Msg;
import cn.szzsi.common.exception.BusinessException;
import cn.szzsi.common.kit.*;
import cn.szzsi.common.model.*;
import cn.szzsi.common.model.OrderLog.OrderLogType;
import cn.szzsi.common.model.Payment.PaymentType;
import cn.szzsi.common.model.Product.WeightUnit;
import cn.szzsi.core.kit.UtilDate;
import cn.szzsi.interceptor.JSSDKInterceptor;
import cn.szzsi.interceptor.WechatLoginInterceptor;
import cn.szzsi.service.*;
import cn.szzsi.validator.OrderValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.JFinal;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import javax.servlet.http.Cookie;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;

/**
 * 前台类 - 订单处理
 * 
 */
public class OrderController extends BaseWebPcController<Orders>{

	private Boolean isSaveReceiver;// 是否保存收货地址
	private Integer totalQuantity;// 商品总数
	private Integer totalPoint;// 总积分
	private Double totalWeightGram;// 商品总重量（单位：g）
	private BigDecimal productTotalPrice;// 总计商品价格
	private String memo;// 附言

	private List<CartItem> cartItemList;// 购物车项
	private DeliveryType deliveryType;// 配送方式
	private PaymentConfig paymentConfig;// 支付方式
	private PaymentType paymentType;// 支付类型
	private BigDecimal paymentFee;// 支付手续费
	private BigDecimal amountPayable;// 应付金额（不含支付费用）
	private Orders order;// 订单
	private Receiver receiver;
	private String path;//模板路径
	private String uid;//商户id,也是用户的店铺id
	private Product product;
	private Page<Orders> pager;
	//商户相关资料
	private String appid;//应用ID
	private String secret;//应用密钥
	private String partner;//商户号
	private String key;//支付秘钥
	// 订单列表
	public void list(){
		uid=getLoginMember().getStr("shopId");//用户的shopId对应商户的id(uid),商户的shopId为"-1"
		int pageNumber = getParaToInt("pageNumber",1);
		int pageSize = getParaToInt("pageSize",Orders.DEFAULT_ORDER_LIST_PAGE_SIZE);

		Page<Orders> pager = Orders.dao.getOrderPager(pageNumber,pageSize,getLoginMember().getStr("id"));
		setAttr("pager", pager);
		setAttr("type",getPara("type"));
		pcTemplatePath("order_list.html");
	}

	//订单列表异步加载
	//1.页面
	public void orderListForm(){
		//uid=getLoginMember().getStr("shopId");//用户的shopId对应商户的id(uid),商户的shopId为"-1"
		uid=getPara("shopId");//用户的shopId对应商户的id(uid),商户的shopId为"-1"
		setAttr("type",getPara("type"));
		getTemplatePath(uid,"order_list");

	}

	//2.加载数据
	public void ajaxOrderList(){
		int pageNumber=getParaToInt("pageNumber", 1);//第几页,默认1
		int pageSize=getParaToInt("pageSize", 10);//每页的数量,默认10
		uid=getPara("shopId");
		String type=getPara("type");
		if("logistics".equals(type)){
			List<Object> list=new ArrayList<Object>();
			renderJson(Msg.success(list));
		}else{
			List<Object> list= MemberOrderService.service.getOrdersByType(pageNumber,pageSize,getLoginMember().getStr("id"),type);
			renderJson(Msg.success(list));
		}
	}

	// 订单信息(从购物车进入)
	public void info() {
		Member member = getLoginMember();
		cartItemList = member.getCartItemList();
		productTotalPrice = new BigDecimal("0");
		totalQuantity = 0;
		for (CartItem cartItem : cartItemList) {
			totalQuantity += cartItem.getQuantity();
			Product product = cartItem.getProduct();
			if (product.getStore() != null && (cartItem.getQuantity() + product.getFreezeStore()) > product.getStore()) {
				renderHtml("<script>alert('商品库存不足，请返回修改!');history.go(-1);</script>");
				return;
			}
			productTotalPrice = product.getPreferentialPrice(member).multiply(new BigDecimal(cartItem.getQuantity())).add(productTotalPrice);
			productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);//价格统一化
		}
		setAttr("totalQuantity",totalQuantity);
		setAttr("loginMember", member);
		setAttr("productTotalPrice", productTotalPrice);
		setAttr("allPaymentConfig", PaymentConfig.dao.getAll());//支付方式
		setAttr("userBalance", member.getUserBalance());

		setAttr("cartItemList", cartItemList);
		String receiverId = getPara("receiverId");
		setAttr("receiverId", receiverId);
		if (StrKit.notBlank(receiverId)) {
			Receiver selecttReceiver = Receiver.dao.findById(receiverId);
			setAttr("selecttReceiver", selecttReceiver);
		}

		//判断浏览器类型,如果不是微信浏览器访问,支付方式列表不显示微信支付(因为公众号支付没有openid)
		String userAgent=getRequest().getHeader("user-agent").toLowerCase();//获取浏览器类型
		if(userAgent.indexOf("micromessenger")!=-1){//微信浏览器访问
			setAttr(CommonUtil.BROWSER_TYPE,"weixinBrowser");
		}
		pcTemplatePath("order_info.html");
	}



	// 订单保存
	@Before({OrderValidator.class, Tx.class})
	public void save() throws BusinessException {
		totalQuantity = 0;
		Member member=getLoginMember();
		String paymentConfigId = getPara("paymentConfig_id","");
		memo = getPara("memo");
		receiver = getModel(Receiver.class);
		Integer paidPoints = getParaToInt("payPoints",0);
		BigDecimal paidDeposit = new BigDecimal(getPara("payDeposit", "0"));
		BigDecimal paidPointsAsDeposit = new BigDecimal(paidPoints).divide(new BigDecimal(100));
		/*if (paidPoints > 0 || paidDeposit.compareTo(new BigDecimal(0)) > 0){
			int updated = Db.update("UPDATE mall_user_balance SET balance = balance - ?, point = point - ? WHERE mid = ? AND balance >= ? AND point >= ?", paidDeposit, paidPoints, member.getId(), paidDeposit, paidPoints);
			if (updated != 1){
				addActionError("积分或余额不足");
				return;
			}
		}*/
		productTotalPrice = new BigDecimal("0");
		totalWeightGram = 0D;
		List<Product>productList=new ArrayList<>();
		cartItemList = member.getCartItemList();
		for (CartItem cartItem : cartItemList) {
			Product product = cartItem.getProduct();
			productList.add(product);
			if (product.getStore() != null && (cartItem.getQuantity() + product.getFreezeStore() > product.getStore())) {
				addActionError("商品[" + product.getName() + "]库存不足！");
				return;
			}
			if (product.getStore() != null) {
				product.set("freezeStore", product.getFreezeStore() + cartItem.getQuantity());
				if (product.getIsOutOfStock()) {
					product.getProductAttributeMapStore();
					HtmlService.service.productContentBuildHtml(product);
				}
				product.update();
			}

			Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());
			totalWeightGram = ArithUtil.add(totalWeightGram, ArithUtil.mul(weightGram, cartItem.getQuantity()));
			totalQuantity += cartItem.getQuantity();
			productTotalPrice = product.getPreferentialPrice(member).multiply(new BigDecimal(cartItem.getQuantity())).add(productTotalPrice);
			productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);
		}
		//BigDecimal deliveryFee = deliveryType.getDeliveryFee(totalWeightGram);
		paymentConfig = PaymentConfig.dao.findById(paymentConfigId);//支付方式
		if (StrKit.notBlank(receiver.getId())) {
			receiver = Receiver.dao.findById(receiver.getId());//收货地址
		}
		String orderPlateFormId=StrKit.getRandomUUID();//平台总订单id
		//给商户分单(未支付订单)
		Map<String, List<Product>>listMap=convert(productList);
		BigDecimal allDeliveryFee=new BigDecimal(0);//所有商品运费(可能来自不同的商户)
		for (String shopId : listMap.keySet()) {
			List<Product>products=listMap.get(shopId);//商品所属的商户
			Double businessTotalWeightGram = 0D;//商户商品总重量
			Integer businessTotalQuantity=0;//商户商品总数量
			BigDecimal deliveryFee=new BigDecimal(0);//该商户的运费
			BigDecimal businessProductTotalPrice=new BigDecimal(0);//商户商品总价
			String businessOrderId=StrKit.getRandomUUID();
			for(Product product:products){
				Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());
				businessTotalWeightGram = ArithUtil.add(businessTotalWeightGram,weightGram);
				businessTotalQuantity+=1;
				businessProductTotalPrice = product.getPreferentialPrice(member).add(businessProductTotalPrice);
				OrderItemService.service.saveOrderItem(product, 1, businessOrderId, member);//商品项(商品明细列表)
			}
			deliveryType = DeliveryTypeService.service.getDeliverType(receiver, shopId);
			if(deliveryType!=null){
				deliveryFee = DeliveryTypeService.service.getDeliveryFee(Double.valueOf(businessTotalWeightGram), deliveryType);//计算运费(商户)
			}
			allDeliveryFee=allDeliveryFee.add(deliveryFee);//计算运费(所有商户运费)
			//创建商户订单
			order=OrderService.service.createBusinessOrder(businessOrderId,orderPlateFormId,deliveryType,businessProductTotalPrice,deliveryFee,businessTotalWeightGram,businessTotalQuantity,receiver,getPara("memo"),member,shopId,paymentConfig);
			OrderService.service.saveOrderLog(OrderLogType.create.ordinal(), order, "订单创建");// 订单日志
			//创建商户订单


		}
		paymentFee = paymentConfig.getBusinessPaymentFee(productTotalPrice.add(allDeliveryFee), paymentConfig);
		BigDecimal totalAmount = productTotalPrice.add(allDeliveryFee).add(paymentFee);//商品费用+配送费用+支付手续费
		// 待支付
		BigDecimal toPay = totalAmount.subtract(paidDeposit).subtract(paidPointsAsDeposit);
		int payStatus = toPay.compareTo(new BigDecimal(0));
		if (payStatus < 0){
			throw new BusinessException("用户错误");
		}
		//创建平台总订单
		OrdersPlateform ordersPlateform=OrderService.service.createPlateFormOrder(orderPlateFormId,totalQuantity,productTotalPrice,allDeliveryFee,paymentFee,paidDeposit,paidPoints,paidPointsAsDeposit,paymentConfig,member);
		OrderService.service.saveOrderLog(OrderLogType.create.ordinal(), ordersPlateform, "订单创建");// 订单日志
		//创建平台总订单


		//如果该订单用了余额或者积分支付,则添加余额支付明细
        /*if (order.getPaidDeposit().compareTo(new BigDecimal(0)) > 0) {
            UserBalanceDetailService.service.savePaymentInfo(member.getId(), order.getPaidDeposit(), UserBalanceDetail.BalanceType.memberPayment.ordinal(), member.getShopId(), order.getOrderSn());//支付明细
        }
        if (order.getPaidPoints() > 0) {
            UserPointDetailService.service.saveInfo(member.getId(), paidPoints, UserPointDetail.PointDetailType.memberPayment.ordinal(), "订单支付(积分抵扣)");//积分明细
        }*/
		//如果该订单用了余额或者积分支付,则添加余额支付明细
		//OrderService.service.saveOrderLog(OrderLogType.create.ordinal(), order, "订单创建");// 订单日志
		//将Cookie购物车总数量改为0
        /*Cookie quantity = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_TOTAL_QUANTITY, "0");
        quantity.setPath(getRequest().getContextPath() + "/");
        quantity.setMaxAge(CartItemCookie.CART_ITEM_LIST_COOKIE_MAX_AGE);
        getResponse().addCookie(quantity);*/
		//将Cookie购物车总数量改为0

		setAttr("ordersPlateform", ordersPlateform);
		setAttr("openId", member.getOpenid());
		setAttr("paymentFee", paymentFee);
		setAttr("paymentConfig", paymentConfig);
		if (paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.weixin) {//微信支付
			appid = _Config.p.get("wechat_appid");//应用ID
			secret = _Config.p.get("wechat_secret");//应用密钥
			WeixinConfig weixinConfig = new WeixinConfig();
			weixinConfig.setAppid(appid);
			weixinConfig.setSecret(secret);
			ApiConfigKit.setThreadLocalApiConfig(getApiConfig(weixinConfig));

			JsTicket jsApiTicket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
			String jsapi_ticket = jsApiTicket.getTicket();
			String nonce_str = create_nonce_str();
			// 注意 URL 一定要动态获取，不能 hardcode.
			String url = _Config.p.get("mall_web.url") + getRequest().getServletPath();
			String qs = getRequest().getQueryString(); // 参数
			if (qs != null) {
				url = url + "?" + (getRequest().getQueryString());
			}
			String timestamp = create_timestamp();
			// 这里参数的顺序要按照 key 值 ASCII 码升序排序,注意这里参数名必须全部小写，且必须有序
			String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
			String signature = HashKit.sha1(str);
			setAttr("appId", ApiConfigKit.getApiConfig().getAppId());
			setAttr("nonceStr", nonce_str);
			setAttr("timestamp", timestamp);
			setAttr("url", url);
			setAttr("signature", signature);
			setAttr("base", getRequest().getContextPath());
			setAttr("jsapi_ticket", jsapi_ticket);
			setAttr("openId", member.getOpenid());
		}
		pcTemplatePath("order_result.html");
		//wapTemplatePath("order_result.html");
	}

	// 订单详情
	public void view() {
		id = getPara("id","");
		order = Orders.dao.findById(id);
		totalPoint = 0;
		if (getSystemConfig().getPointType() == PointType.productSet) {
			for (OrderItem orderItem : order.getOrderItemList()) {
				totalPoint = orderItem.getProduct().getInt("point") * orderItem.getInt("productQuantity") + totalPoint;
			}
		} else if (getSystemConfig().getPointType() == PointType.orderAmount) {
			totalPoint = order.getBigDecimal("productTotalPrice").multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
		}
		setAttr("order", order);
		pcTemplatePath("order_view.html");

	}

	//买家申请退款
	public void applyRefund(){
		String id=getPara("id");
		order=Orders.dao.findById(id);
		order.set("paymentStatus", Orders.PaymentStatus.inRefund.ordinal());//支付状态改为申请退款中
		order.update();

		// 订单日志
		OrderService.service.saveOrderLog(OrderLogType.refund.ordinal(),order,"买家申请退货款");

		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, "操作成功！");
		renderJson(jsonMap);

	}

	//买家确认收货
	@Before(Tx.class)
	public void sureReceipt() {
		String orderId = getPara("id");
		if (StrKit.isBlank(orderId)) {
			ajaxJsonWarnMessage("订单ID不能空！");
			return;
		}
		order = Orders.dao.findById(orderId);

		if (order.getOrderStatusValue() == Orders.OrderStatus.completed) {
			ajaxJsonWarnMessage("此订单已经完成！");
		} else if (order.getOrderStatusValue() == Orders.OrderStatus.invalid) {
			ajaxJsonErrorMessage("此订单已经作废！");
		} else {
			order.set("orderStatus", Orders.OrderStatus.valueOf(Orders.OrderStatus.completed.name()).ordinal());
			updated(order);

			// 积分处理
			Integer totalPoint = 0;
			if (getSystemConfig().getPointType() == PointType.orderAmount) {
				totalPoint = order.getBigDecimal("productTotalPrice").multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
			} else if (getSystemConfig().getPointType() == PointType.productSet) {
				for (OrderItem orderItem : order.getOrderItemList()) {
					totalPoint = orderItem.getProduct().getInt("point") * orderItem.getInt("productQuantity") + totalPoint;
				}
			}
			if (totalPoint > 0) {
				Member member = order.getMember();
				member.set("point",member.getInt("point") + totalPoint);
				MemberRank upMemberRank = MemberRank.dao.getUpMemberRankByPoint(member.getInt("point"),member.getStr("shopId"));
				if (upMemberRank != null && member.getInt("point") >= upMemberRank.getInt("point")) {
					member.set("memberRankId",upMemberRank.getStr("id"));
				}
				member.update();
			}
			// 订单日志
			OrderService.service.saveOrderLog(OrderLogType.completed.ordinal(),order,"买家确认收货");
			ajaxJsonSuccessMessage("您的操作已成功！");
		}
	}

	//买家申请退货
	public void applyReshiped(){
		String id=getPara("id");
		order=Orders.dao.findById(id);
		order.set("shippingStatus", Orders.ShippingStatus.inReshiped.ordinal());//支付状态改为申请退款中
		order.update();

		// 订单日志
		OrderService.service.saveOrderLog(OrderLogType.reship.ordinal(),order,"买家申请退货");

		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, "操作成功！");
		renderJson(jsonMap);

	}

	//买家评价
	@Before(JSSDKInterceptor.class)
	public void evaluateEdit(){
		uid=getPara("shopId");//用户的shopId对应商户的id(uid),商户的shopId为"-1"
		SiteConfig siteConfig= SiteConfig.getByShopId(uid);
		String shopAlias=siteConfig.getStr("shopAlias");
		setAttr("siteConfig",siteConfig);
		setAttr("shopAlias",shopAlias);
		setAttr("shopId",uid);
		id = getPara("id","");
		order = Orders.dao.findById(id);
		setAttr("order",order);
		setAttr("base", getRequest().getContextPath());
		getTemplatePath(uid,"order_evaluate");
	}
	//保存买家评论
	public void evaluateSave(){
		String type=getPara("type");
		String orderId=getPara("orderId");
		Member member=getLoginMember();
		String memberId=member.getStr("id");
		uid=member.getStr("shopId");
		String content=getPara("content","好评!");//默认好评
		String imageStror=getPara("imageStr");
		String productId=getPara("productId");
		Integer countStar=getParaToInt("countStar");//星级评分
		ProductEvaluate.saveEvaluate(productId,content,imageStror,countStar,memberId,uid);
		OrderItem orderItem= OrderItem.dao.getByOrderIdAndProductId(orderId,productId);
		if(orderItem!=null){
			orderItem.set("isEvaluate",Orders.OrderEvaluate.alreadyevaluate.ordinal()).update();//已评价
		}
		List<OrderItem> orderItemList= OrderItem.dao.getByOrderIdAndStatus(orderId,Orders.OrderEvaluate.notevaluate.ordinal());
		if(orderItemList.size()==0){
			//如果订单全部评价,将订单状态改为已评价
			Orders.dao.findById(orderId).set("orderEvaluate",Orders.OrderEvaluate.alreadyevaluate.ordinal()).update();
		}
		//查询该订单的商品是否已经全部评价,若是,则将订单状态改为已评价


		renderJson(Msg.SUCCESS);
	}
	public void evaluateimage(){
		String type=getPara("type");
		Map<String,String> map=new HashMap<String,String>();
		if("wx".equals(type)){
			String shopId=getPara("shopId");
			String serverId=getPara("serverId");//微信服务器文件id
			SiteConfig siteConfig= SiteConfig.getByShopId(shopId);
			/*String appid=siteConfig.getStr("appid");
			String secret=siteConfig.getStr("secret");
			String apiid=siteConfig.getStr("apiid");*/

			String access_token= WeixinUtil.getAccessToken(shopId);
			System.out.println("accesstoken00000000:"+access_token);
			System.out.println("media_id00000000:"+serverId);
			String imageWeixinUrl="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+serverId;
			String filename = QRCodeUtil.savePic(imageWeixinUrl, UtilDate.getOrderNum()+"evaluate.png", JFinal.me().getServletContext().getRealPath("/upload/evaluate"));
			int start=filename.indexOf("/upload");
			String imagePath=filename.substring(start);
			map.put("imageurl",imagePath);
			map.put("random",CommonUtil.getUUID());
			map.put("code","0");

			//获取accessToken
		/*String param="apiid="+apiid;
		String reqUrl= ReqUrlUtil.getAccessToken;
		String result= HttpKit.post(reqUrl,null,param);
		JSONObject obj = new JSONObject(result);
		String access_token=obj.getJSONObject("data").get("access_token").toString();

		String imageWeixinUrl="https://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+serverId;
		System.out.println("imageWeixinUrl-----------------"+imageWeixinUrl);
		String filename = QRCodeUtil.savePic(imageWeixinUrl,UtilDate.getOrderNum()+"evaluate.png",JFinal.me().getServletContext().getRealPath("/upload/evaluate/"));*/
		}else{
			UploadFile uploadFile = getFile("evaluateimage");
			String imageurl="";
			if(uploadFile!=null){
				imageurl = _Config.p.get("file.url")+uploadFile.getFileName();//网店logo路径
			}
			map.put("imageurl",imageurl);
			map.put("random",CommonUtil.getUUID());
		}
		renderJson(map);

	}
	@Clear
	public void deleteWebImage(){
		renderJson(Msg.SUCCESS);

	}

	// 支付确认
	public void confirm() {
		uid=getLoginMember().getStr("shopId");
		SiteConfig siteConfig= SiteConfig.getByShopId(uid);
		amountPayable = new BigDecimal(getPara("amountPayable","0"));
		paymentType = PaymentType.valueOf(getPara("paymentType"));
		String paymentConfigId = getPara("paymentConfig.id","");
		String orderId = getPara("order.id");
		if (paymentType == PaymentType.recharge) {
			if (amountPayable == null) {
				addActionError("请输入充值金额！");
				return;
			}
			if (amountPayable.compareTo(new BigDecimal("0")) <= 0) {
				addActionError("充值金额必须大于0！");
				return;
			}
			if (amountPayable.scale() > getSystemConfig().getOrderScale()) {
				addActionError("充值金额小数位超出限制！");
				return;
			}
			if (StringUtils.isEmpty(paymentConfigId)) {
				addActionError("请选择支付方式！");
				return;
			}
			if (StrKit.notBlank(paymentConfigId)){
				paymentConfig = PaymentConfig.dao.findById(paymentConfigId);
			}
			paymentFee = paymentConfig.getPaymentFee(amountPayable);
		} else {
			if (StringUtils.isEmpty(orderId)) {
				addActionError("订单信息错误！");
				return;
			}
			order = Orders.dao.findById(orderId);
			paymentConfig = order.getPaymentConfig();
			paymentFee = order.getBigDecimal("paymentFee");
			amountPayable = order.getBigDecimal("totalAmount").subtract(paymentFee).subtract(order.getBigDecimal("paidAmount"));
			if(paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.weixin){//微信支付
				String configObjectStore=paymentConfig.get("configObjectStore");//获取支付信息
				JSONObject obj = new JSONObject(configObjectStore);
				appid=obj.get("appid").toString();
				secret=obj.get("secret").toString();
				WeixinConfig weixinConfig=new WeixinConfig();
				weixinConfig.setAppid(appid);
				weixinConfig.setSecret(secret);
				ApiConfigKit.setThreadLocalApiConfig(getApiConfig(weixinConfig));

				JsTicket jsApiTicket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
				String jsapi_ticket = jsApiTicket.getTicket();
				String nonce_str = create_nonce_str();
				// 注意 URL 一定要动态获取，不能 hardcode.
				String url=CommonUtil.getBusinessWebName(siteConfig)+getRequest().getServletPath();
				String qs = getRequest().getQueryString(); // 参数
				if (qs != null) {
					url = url + "?" + (getRequest().getQueryString());
				}
				String timestamp = create_timestamp();
				// 这里参数的顺序要按照 key 值 ASCII 码升序排序
				//注意这里参数名必须全部小写，且必须有序
				String str = "jsapi_ticket=" + jsapi_ticket +
						"&noncestr=" + nonce_str +
						"&timestamp=" + timestamp +
						"&url=" + url;

				String signature = HashKit.sha1(str);
				setAttr("appId", ApiConfigKit.getApiConfig().getAppId());
				setAttr("nonceStr", nonce_str);
				setAttr("timestamp", timestamp);
				setAttr("url", url);
				setAttr("signature", signature);
				setAttr("base", getRequest().getContextPath());
				setAttr("jsapi_ticket", jsapi_ticket);
				setAttr("openId",getLoginMember().getStr("openid"));

			}

		}
		setAttr("order", order);
		setAttr("paymentType", paymentType);
		setAttr("amountPayable", amountPayable);
		setAttr("paymentFee", paymentFee);
		setAttr("paymentConfig", paymentConfig);
		getTemplatePath(uid,"payment_confirm");

	}

	public ApiConfig getApiConfig(WeixinConfig weixinConfig) {
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		//ac.setToken(AConfig.p.get("token"));
		ac.setAppId(weixinConfig.getAppid());
		ac.setAppSecret(weixinConfig.getSecret());

		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(_Config.p.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(_Config.p.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}



	/**
	 * 获取配送费用
	 */
	public void getDeliveryFee() {
		String shopId = getPara("shopId");//店铺id
		String totalWeightGram = getPara("totalWeightGram");//商品总重量
		String receiverId = getPara("receiverId");//收货地区id
		Receiver receiver = Receiver.dao.findById(receiverId);//收货地址实体类
		Integer provinceId = receiver.getProvinceId();//省id
		Integer cityId = receiver.getCityId();//市id
		Integer areaId = receiver.getAreaId();//区id
		String allAreaId = provinceId + "," + cityId + "," + areaId + ",0";
		DeliveryAreaRelation deliveryAreaRelation = DeliveryAreaRelation.dao.findFirst("select * from mall_delivery_area_relation where shopId=? and areaId in (" + allAreaId + ")", shopId);
		if (deliveryAreaRelation != null) {//用户的收货地区在商户所设置的模板中
			//1.查看运费模板
			DeliveryType deliveryType = DeliveryType.dao.findById(deliveryAreaRelation.getDeliveryTypeId());
			//2.计算运费
			BigDecimal deliveryFee = DeliveryTypeService.service.getDeliveryFee(Double.valueOf(totalWeightGram), deliveryType);
			renderJson(Ret.ok("deliveryFee", deliveryFee + ""));
		} else {//用户的收货地区不在商户所设置的模板中,将运费置为0
			renderJson(Ret.ok("deliveryFee", "0.00"));
		}

	}

	public void getAllDeliverFee(){
		Member member = getLoginMember();
		String receiverId = getPara("receiverId");//收货地区id
		Receiver receiver = Receiver.dao.findById(receiverId);//收货地址实体类
		Integer provinceId = receiver.getProvinceId();//省id
		Integer cityId = receiver.getCityId();//市id
		Integer areaId = receiver.getAreaId();//区id
		String allAreaId = provinceId + "," + cityId + "," + areaId + ",0";

		List<Product>productList=new ArrayList<>();
		cartItemList = member.getCartItemList();
		for (CartItem cartItem : cartItemList) {
			Product product = cartItem.getProduct();
			productList.add(product);
		}
		Map<String, List<Product>>listMap=convert(productList);
		BigDecimal allDeliveryFee=new BigDecimal(0);
		for (String shopId : listMap.keySet()) {
			List<Product>products=listMap.get(shopId);
			totalWeightGram = 0D;
			for(Product product:products){
				Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnitValue());
				totalWeightGram = ArithUtil.add(totalWeightGram,weightGram);
			}
			DeliveryAreaRelation deliveryAreaRelation = DeliveryAreaRelation.dao.findFirst("select * from mall_delivery_area_relation where shopId=? and areaId in (" + allAreaId + ")", shopId);
			if(deliveryAreaRelation!=null){
				//1.查看运费模板
				DeliveryType deliveryType = DeliveryType.dao.findById(deliveryAreaRelation.getDeliveryTypeId());
				//2.计算运费
				BigDecimal deliveryFee = DeliveryTypeService.service.getDeliveryFee(Double.valueOf(totalWeightGram), deliveryType);
				allDeliveryFee=allDeliveryFee.add(deliveryFee);
			}else{
				allDeliveryFee=allDeliveryFee.add(new BigDecimal(0));
			}
		}
		System.out.println("allDeliveryFee------------"+allDeliveryFee);
		renderJson(Ret.ok("deliveryFee", allDeliveryFee));
	}

	public static Map<String, List<Product>> convert(List<Product> products) {
		Map<String, List<Product>> converted = new LinkedHashMap<>();

		for (Product p : products){
			List<Product> shopProducts = converted.get(p.getUid());
			if (shopProducts == null){
				shopProducts = new ArrayList<>();
				converted.put(p.getUid(), shopProducts);
			}
			shopProducts.add(p);
		}
		//System.out.println("converted-----"+converted);
		return converted;
	}



}
